// personal.js
Page({
    data: {
        name: '',
        genderOptions: ['男', '女'], // 只包含“男”和“女”
        genderIndex: 0,
        phone: '',
        email: '',
        address: ''
    },

    onLoad: function (options) {
        // 从本地存储中获取表单数据
        wx.getStorage({
            key: 'personalFormData',
            success: (res) => {
                const formData = res.data;
                this.setData({
                    name: formData.name || '',
                    genderIndex: this.data.genderOptions.indexOf(formData.gender) || 0,
                    phone: formData.phone || '',
                    email: formData.email || '',
                    address: formData.address || ''
                });
            },
            fail: (err) => {
                console.log('获取缓存数据失败', err);
            }
        });
    },

    onNameInput(e) {
        this.setData({name: e.detail.value});
    },

    onGenderChange(e) {
        this.setData({genderIndex: e.detail.value});
    },

    onPhoneInput(e) {
        this.setData({phone: e.detail.value});
    },

    onEmailInput(e) {
        this.setData({email: e.detail.value});
    },

    onAddressInput(e) {
        this.setData({address: e.detail.value});
    },

    submitForm() {
        const {name, genderIndex, phone, email, address} = this.data;
        const gender = this.data.genderOptions[genderIndex];

        if (!name || !phone) {
            wx.showToast({
                title: '姓名和电话为必填项',
                icon: 'none',
                duration: 2000
            });
            return;
        }

        const formData = {
            name,
            gender,
            phone,
            email,
            address
        };

        console.log('提交的表单数据:', formData);

        // 异步保存到本地存储
        wx.setStorage({
            key: 'personalFormData',
            data: formData,
            success: function () {
                wx.showToast({
                    title: '提交成功',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail: function () {
                wx.showToast({
                    title: '保存失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        });
    }
});
